package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Cookie_infServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //标识符
        int i = 0;
        //获取前端传送过来的数据
        String cookie_name = req.getParameter("cookie_name");
        //创建session 存储
        HttpSession session = req.getSession();
        //存储cookie
        ArrayList<Object> list = new ArrayList<>();
        //获取Cookie 的信息
        Cookie[] cookies = req.getCookies();

        if (cookies != null) {
            for (Cookie cook : cookies) {
                //添加到list
                list.add(URLDecoder.decode(cook.getName(),"UTF-8"));
                //判断cookie的名字等于 索要查询的cookie的名字
                if (URLDecoder.decode(cook.getName(),"UTF-8").equals(cookie_name)) {
                    //把集合存储到session 中
                    session.setAttribute("cookieinfo", "cookiename:" + URLDecoder.decode(cook.getName(),"UTF-8") + "cookievalue:" + cook.getValue());
                    i++;
                }
            }
            //没查询到
            if (i == 0) {
                session.setAttribute("cookieinfo", "无此cookie");
            }
        }
        //不能执行for,一个cookie 没有
        else {
            session.setAttribute("cookieinfo", "现在没有cookie");
        }
        //存储所有的cookie name
        session.setAttribute("cookieinfo_List", list);
        //跳转回页面
        req.getRequestDispatcher("/cookieinfo.jsp").forward(req, resp);
    }
}
